package comWorld.blog;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import oracle.net.aso.i;

import org.apache.jasper.tagplugins.jstl.core.Out;

import webManage.FileManage;

import com.gjs.tools.JDBC.JDBCTools;
import com.sun.org.apache.bcel.internal.generic.RETURN;

public class BlogInfoManage {
	
	private static String GET_BLOG_INFO_SQL = "select bi.user_id userId, bi.blog_id blogId, title, abstract blogAbstract, " +
			"content_url contentUrl, tags ctags, bi.catalog_id catalogId, bcat.name catalogName, type, origin_url originUrl, privacy, deny_comment denyComment, " +
			"has_publish hasPublish, write_date writeDate, read_count readCount, " + 
			"collect_count collectCount, praise_count praiseCount, comment_count commentCount from blog_info bi, blog_catalog bcat where bi.user_id = ? AND bi.catalog_id = bcat.catalog_id";
	
	public static BlogInfos getDraftInfos(int userId) {
		String sql = GET_BLOG_INFO_SQL +  " AND has_publish = 0";
		List<BlogInfo> blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId);
		return new BlogInfos(userId, blogs);
	}
	
	public static BlogInfos getBlogInfos(int userId) {
		String sql = GET_BLOG_INFO_SQL +  " AND has_publish = 1 AND privacy = 0";
		List<BlogInfo> blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId);
		return new BlogInfos(userId, blogs);
	}
	
	public static BlogInfos getBlogInfos(int userId, int privacy) {
		String sql = GET_BLOG_INFO_SQL +  " AND has_publish = 1";
		if (privacy == 1)
			sql += " AND privacy = 0";
		List<BlogInfo> blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId);
		return new BlogInfos(userId, blogs);
	}
	
	public static BlogInfos getBlogInfosByCatalogIdAndSort(int userId, int catalogId, String sort) {
		String sql = GET_BLOG_INFO_SQL + " AND has_publish = 1 AND privacy = 0";
		if (catalogId != 0)
			sql += " AND bi.catalog_id = ?";
		if (sort.equals("time"))
			sql += " ORDER BY write_date DESC";
		else if (sort.equals("hot"))
			sql += " ORDER BY read_count DESC";
		List<BlogInfo> blogs;
		if (catalogId == 0)
			blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId);
		else 
			blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId, catalogId);
		BlogInfos blogInfos = new BlogInfos(userId, blogs);
		return blogInfos;
	}
	
	public static BlogInfos getBlogInfosByCatalogIdAndSort(int userId, int catalogId, String sort, int privacy) {
		String sql = GET_BLOG_INFO_SQL + " AND has_publish = 1";
		if (privacy == 1)
			sql += " AND privacy = 0";
		
		if (catalogId != 0)
			sql += " AND bi.catalog_id = ?";
		if (sort.equals("time"))
			sql += " ORDER BY write_date DESC";
		else if (sort.equals("hot"))
			sql += " ORDER BY read_count DESC";
		List<BlogInfo> blogs;
		if (catalogId == 0)
			blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId);
		else 
			blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId, catalogId);
		BlogInfos blogInfos = new BlogInfos(userId, blogs);
		return blogInfos;
	}
	
	public static BlogInfo getDraftInfo(int userId, int draftId) {
		String sql = GET_BLOG_INFO_SQL +  " AND has_publish = 0 AND bi.blog_id = ?";
		return JDBCTools.getObject(BlogInfo.class, sql, userId, draftId);
	}
	
	public static BlogInfo getBlogInfo(int userId, int blogId) {
		String sql = GET_BLOG_INFO_SQL +  " AND has_publish = 1 AND bi.blog_id = ?";
		return JDBCTools.getObject(BlogInfo.class, sql, userId, blogId);
	}
	
	public static boolean addNewBlog(BlogInfo blog) {
		String sql = "insert into blog_info values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		return JDBCTools.insert(sql, blog.getUserId(), blog.getBlogId(), blog.getTitle(), blog.getBlogAbstract(),
				blog.getContentUrl(), blog.getCtags(), blog.getCatalogId(), blog.getType(), blog.getOriginUrl(),
				blog.getPrivacy(), blog.getDenyComment(), blog.getHasPublish(), blog.getWriteDate(), blog.getReadCount(),
				blog.getCollectCount(), blog.getPraiseCount(), blog.getCommentCount()) > 0;
	}
	
	public static String saveBlogContent(int blogId, int userId, String content, ServletContext app) {
		String contentUrl = app.getRealPath(FileManage.MAINDIR + userId + "/blog/" + blogId + ".txt");
		File file = FileManage.createNewFile(contentUrl);
		try {
			BufferedWriter out = null;
			try {
				out =  new BufferedWriter(new FileWriter(file));
				out.write(content);
			} finally {
				if (out != null)
					out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return contentUrl;
	}
	
	public static boolean updateBlogBasicInfo(BlogInfo blog) {
		String sql = "UPDATE blog_info SET title = ?, abstract = ?, " +
			"tags = ?, catalog_id = ?, type = ?, origin_url = ?, privacy = ?, deny_comment = ?, " +
			"has_publish = ?, write_date = ? where blog_id = ?";
		return JDBCTools.update(sql, blog.getTitle(), blog.getBlogAbstract(), blog.getCtags(), blog.getCatalogId(), blog.getType(),
				blog.getOriginUrl(), blog.getPrivacy(), blog.getDenyComment(), blog.getHasPublish(), blog.getWriteDate(), blog.getBlogId()) > 0;
	}
	
	public static BlogInfos getHotBlogs(int userId) {
		String sql = "SELECT user_id userId, blog_id blogId, title FROM blog_info WHERE has_publish = 1 AND privacy = 0 ";
		List<BlogInfo> blogs = null;
		if (userId != 0) {
			sql += "AND user_id = ? AND rownum <= 8 ORDER BY read_count DESC";
			blogs = JDBCTools.getObjects(BlogInfo.class, sql, userId);
		} else {
			sql += "AND rownum <= 20 ORDER BY read_count DESC";
			blogs = JDBCTools.getObjects(BlogInfo.class, sql);
		}
		return new BlogInfos(userId, blogs);
	}
	
	
	
	public static boolean addPraiseCount(int blogId, int userId) {
		String sql = "SELECT user_id FROM blog_praise WHERE blog_id = ? AND user_id = ?";
		if (JDBCTools.queryHasData(sql, blogId, userId) == 0) {
			sql = "INSERT INTO blog_praise VALUES(?,?)";
			JDBCTools.insert(sql, blogId, userId);
			sql = "UPDATE blog_info SET praise_count = praise_count + 1 WHERE blog_id = ?";
			JDBCTools.update(sql, blogId);
			return true;
		}
		return false;
	}
	
	public static String getBlogContent(int blogId, int userId, ServletContext app) {
		String contentPath = app.getRealPath(FileManage.MAINDIR + userId + "/blog/" + blogId + ".txt");
		try {
			BufferedReader reader = new BufferedReader(new FileReader(contentPath));
			try {
				StringBuilder content = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					content.append(line);
				}
				return content.toString();
			} finally {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static boolean deleteBlog(int userId, int blogId, ServletContext app) {
		String sql = "DELETE FROM blog_info WHERE blog_id = ?";
		if (JDBCTools.update(sql, blogId) > 0) {
			String contentPath = app.getRealPath(FileManage.MAINDIR + userId + "/blog/" + blogId + ".txt");
			File content = new File(contentPath);
			content.delete();
			return true;
		}
		return false;
	}
	
	public static List<BlogLog> getBlogLogs(int userId, String ft, int privacy) {
		String sql = "SELECT bi.blog_id blogId, bi.user_id userId, ui.user_name userName, ui.head_image userHeadImage, bi.title title, "
				+ "bi.type type, bi.write_date writeTime, bi.comment_count commentCount, bi.read_count readCount, bi.praise_count praiseCount "
				+ "FROM blog_info bi, user_info ui WHERE bi.user_id = ui.id AND bi.has_publish = 1 AND ";
		if (privacy == 1)
			sql += "privacy = 0 AND ";
		
		String self = sql + "bi.blog_id IN (SELECT blog_id FROM blog_info WHERE user_id = ? AND has_publish = 1) ORDER BY bi.write_date DESC";
		String fellow = sql + "bi.blog_id IN (SELECT blog_id FROM blog_info WHERE has_publish = 1 AND user_id IN (SELECT friend_id FROM social_info WHERE user_id = ?)) ORDER BY bi.write_date DESC";
		List<BlogLog> blogLogs = null;
		List<BlogLog> selfBlogLogs = null;
		List<BlogLog> fellowBlogLogs = null;
		if (ft.equals("all")) {
			selfBlogLogs = JDBCTools.getObjects(BlogLog.class, self, userId);
			fellowBlogLogs = JDBCTools.getObjects(BlogLog.class, fellow, userId);
			int lastIndex = 0;
			for (BlogLog blogLog : selfBlogLogs) {
				boolean flag = false;
				for (int i = lastIndex; i < fellowBlogLogs.size(); i++) {
					if (blogLog.getWriteTime().compareTo(fellowBlogLogs.get(i).getWriteTime()) > 0) {
						fellowBlogLogs.add(i, blogLog);
						lastIndex = i;
						flag = true;
						break;
					}
				}
				if (!flag) {
					lastIndex = fellowBlogLogs.size();
					fellowBlogLogs.add(lastIndex, blogLog); 
				}
			}
			blogLogs = fellowBlogLogs;
		} else if (ft.equals("self")) {
			blogLogs = JDBCTools.getObjects(BlogLog.class, self, userId);
		} else if (ft.equals("fellow")) {
			blogLogs = JDBCTools.getObjects(BlogLog.class, fellow, userId);
		}
		
		if (userId == 0) {
			sql += "rownum <= 200 ORDER BY bi.write_date DESC";
			blogLogs = JDBCTools.getObjects(BlogLog.class, sql);
		}
		
		return blogLogs;
	}
}
